package com.dxq.test.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.AutoCompleteTextView;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.dxq.test.common.AppManager;
import com.dxq.test.R;
import com.dxq.test.adapter.StockDetailAdapter;
import com.dxq.test.db.Group;
import com.dxq.test.db.Label;
import com.dxq.test.db.LabelGroup;
import com.dxq.test.db.TablesDao;
import com.dxq.test.utils.DialogClickListener;
import com.dxq.test.utils.MyUtil;
import com.dxq.test.view.DevicePopWindow;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

/**
 * Author: zsh
 * Date: 2023/11/15
 * Describe: 群详情页面
 */
@RequiresApi(api = Build.VERSION_CODES.N)
public class GroupDetailActivity extends AppCompatActivity implements View.OnClickListener {

    public TablesDao tablesDao;

    private ImageView ivBack, ivMore;
    private TextView tvTitle, tvSet;
    private RecyclerView recyclerView;

    private StockDetailAdapter mAdapter;
    private List<Label> recordList = new ArrayList<>();
    private List<Label> groupLabelList = new ArrayList<>();

    private Group group = null;
    private String breedingStatus = "";
    private int checkSize = 0;
    private boolean isCheckAll = false;

    private DevicePopWindow devicePopWindow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //添加Activity到堆栈
        AppManager.getAppManager().addActivity(this);
        setContentView(R.layout.activity_group_detail);
        tablesDao = new TablesDao(this);
        group = (Group) getIntent().getSerializableExtra("group");
        initView();
        initAdapter();
    }

    @Override
    protected void onResume() {
        super.onResume();
        getData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在appManager结束当前activity
        AppManager.getAppManager().finishActivity(this);
    }

    private void initView() {
        ivBack = findViewById(R.id.ivBack);
        ivMore = findViewById(R.id.ivMore);
        tvTitle = findViewById(R.id.tvTitle);
        tvSet = findViewById(R.id.tvSet);
        tvTitle.setText(group.getName());
        tvSet.setVisibility(View.VISIBLE);
        tvSet.setText("编辑");

        recyclerView = this.findViewById(R.id.recyclerView);

        ivBack.setOnClickListener(this);
        tvSet.setOnClickListener(this);
        devicePopWindow = new DevicePopWindow(this);
        devicePopWindow.setOnItemChildClickListener(new DevicePopWindow.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull @NotNull View view) {
                devicePopWindow.dismiss();
                switch (view.getId()) {
                    case R.id.tv_1://添加
                        //跳转页面
                        Intent intent = new Intent(GroupDetailActivity.this, StockActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("group", group);
                        intent.putExtras(bundle);
                        intent.putExtra("groupName", group.getName());
                        startActivity(intent);
                        break;

                    case R.id.tv_3://修改群名称
                        addGroupDialog();
                        break;

                    case R.id.tv_4://删除分群
                        MyUtil.normalDialog(GroupDetailActivity.this, "操作提示", "是否删除当前群组？",
                                "取消", "确定", new DialogClickListener() {

                                    @Override
                                    public void onNegativeClick() {

                                    }

                                    @Override
                                    public void onPositiveClick() {
                                        deleteGroup();
                                    }
                                });
                        break;
                }
            }
        });
    }

    private void initAdapter() {
        recyclerView.setLayoutManager(new GridLayoutManager(this, 1));
        recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));//添加分割线
        mAdapter = new StockDetailAdapter(R.layout.item_group_detail, recordList);//
        recyclerView.setAdapter(mAdapter);
        mAdapter.setEmptyView(R.layout.layout_empty);

        //item点击事件
        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter,
                                    @NonNull @NotNull View view, int position) {
                //ToastUtils.showShort("item事件");
            }
        });

        //item子view点击事件
        mAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull @NotNull BaseQuickAdapter adapter,
                                         @NonNull @NotNull View view, int position) {
                if (view.getId() == R.id.tv_delete)
                    //ToastUtils.showShort("child删除事件");
                    deleteLabel(recordList.get(position));

            }
        });
    }

    private void addGroupDialog() {
        View view = getLayoutInflater().inflate(R.layout.add_group_dialog, null);
        AutoCompleteTextView eventName = view.findViewById(R.id.name);
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("添加群")//设置对话框的标题
                .setView(view)
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String name = eventName.getText().toString();
                        if (name.equals("")) {
                            ToastUtils.showShort("填写群名称");
                            return;
                        }
                        //判断该群名称是否已经注册
                        List<Group> groups = tablesDao.queryGroupByName(name);
                        if (null != groups && groups.size() > 0) {
                            ToastUtils.showShort("该群名称已注册");
                            return;
                        }
                        //更新数据
                        group.setName(name);
                        int r = tablesDao.updateGroup(group);
                        if (r == 1) {
                            ToastUtils.showShort("群名更改成功");
                        } else {
                            ToastUtils.showShort("群名更改失败");
                        }
                        tvTitle.setText(group.getName());
                    }
                }).create();
        dialog.show();
    }

    private void deleteGroup() {
        //1、查询出该群内关联的牲畜
        List<LabelGroup> labelGroupList = tablesDao.queryLabelGroupByGroup(group);
        //2、删除关联表中的群与牲畜数据
        tablesDao.deleteLabelGroup(labelGroupList);
        //3、删除群表中的数据
        tablesDao.deleteGroup(group);
        GroupDetailActivity.this.finish();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivBack:
                GroupDetailActivity.this.finish();
                break;

            case R.id.tvSet:
                //设置pop显示位置
                devicePopWindow.showAsDropDown(tvSet, -10, 10);
                backgroundAlpha(0.8f);
                devicePopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        backgroundAlpha(1.0f);
                    }
                });
                break;
        }
    }

    /**
     * 此方法用于改变背景的透明度，从而达到“变暗”的效果
     */
    private void backgroundAlpha(Float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        // 0.0-1.0
        lp.alpha = bgAlpha;
        getWindow().setAttributes(lp);
        // everything behind this window will be dimmed.
        // 此方法用来设置浮动层，防止部分手机变暗无效
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
    }

    private void getData() {
        recordList.clear();
        List<Label> labels = tablesDao.queryLabelForGroup(group);
        if (null != labels && labels.size() > 0) {
            for (Label label : labels) {
                recordList.add(label);
            }
        }
        refreshData();
    }

    //刷新列表数据
    private void refreshData() {
        checkSize = 0;
        if (null != recordList && recordList.size() > 0) {
            for (Label label : recordList) {
                if (label.isCheck()) {
                    checkSize++;
                }
            }
        }
        mAdapter.notifyDataSetChanged();
    }

    //删除群内的牲畜
    private void deleteLabel(Label label) {
        List<LabelGroup> labelGroupList = tablesDao.queryLabelGroupByLabelAndGroup(label, group);
        if (null != labelGroupList && labelGroupList.size() > 0) {
            int result = tablesDao.deleteLabelGroup(labelGroupList.get(0));
            if (result != 1) {
                //删除失败
                ToastUtils.showShort("删除失败");
            } else {
                //删除成功
                ToastUtils.showShort("删除成功");
            }
        }
        getData();
    }

    @Override
    public void onBackPressed() {
        this.finish();
    }
}
